import BaseVenueProcessor from './BaseVenueProcessor.js';
import { getDiSaiGroundPage, getDiSaiGroundUsePage } from '../request.js';

/**
 * 3.5+网球（新基）场地数据处理器
 */
export class ThreePointFiveNewJiProcessor extends BaseVenueProcessor {
  constructor() {
    super();
    this.venueName = '3.5+网球（新基）';
  }

  /**
   * 获取3.5+网球（新基）场地基本信息
   * @param {Object} params - 查询参数
   * @returns {Promise} 请求Promise
   */
  async getGroundPage(params = {}) {
    // 设置默认参数
    const defaultParams = {
      sportHallId: "7",
      page: 1,
      limit: -1,
      whetherOpenUse: 1
    };
    
    // 合并参数
    const requestData = { ...defaultParams, ...params };
    
    return await getDiSaiGroundPage(requestData);
  }

  /**
   * 获取3.5+网球（新基）场地使用信息
   * @param {Object} params - 查询参数
   * @returns {Promise} 请求Promise
   */
  async getGroundUsePage(params = {}) {
    // 设置默认参数
    const defaultParams = {
      sportHallId: "7",
      startDate: "",
      endDate: "",
      page: 1,
      limit: -1
    };
    
    // 合并参数
    const requestData = { ...defaultParams, ...params };
    
    return await getDiSaiGroundUsePage(requestData);
  }

  /**
   * 获取3.5+网球（新基）场地预约设置（兼容方法）
   * @param {Object} params - 查询参数
   * @returns {Promise} 请求Promise
   */
  async getVenueSettings(params = {}) {
    // 根据参数判断是获取基本信息还是使用信息
    if (params.startDate && params.endDate) {
      return await this.getGroundUsePage(params);
    } else {
      return await this.getGroundPage(params);
    }
  }

  /**
   * 验证数据是否有效
   * @param {Object} data - 原始场地数据
   * @returns {boolean} 数据是否有效
   */
  validateData(data) {
    // 检查数据结构是否为 { groundData: [...], useData: [...] }
    if (data.groundData && data.useData) {
      return Array.isArray(data.groundData) && Array.isArray(data.useData);
    }
    
    // 检查数据结构是否为 { data: { records: [...] } }
    const actualData = data.data || data;
    return actualData && 
           actualData.records && 
           Array.isArray(actualData.records);
  }

  /**
   * 按场地名称分组
   * @param {Object} data - 原始场地数据
   * @returns {Map} 场地Map
   */
  groupVenues(data) {
    const venueMap = new Map();
    
    // 处理 { groundData: [...], useData: [...] } 结构
    if (data.groundData) {
      data.groundData.forEach(record => {
        const venueName = record.groundName || record.classRoomName;
        if (!venueMap.has(venueName)) {
          venueMap.set(venueName, {
            name: venueName,
            classRoomId: record.classRoomId,
            sportGroundId: record.sportGroundId,
            timeSlots: []
          });
        }
      });
    } else {
      // 处理 { data: { records: [...] } } 结构
      const actualData = data.data || data;
      actualData.records.forEach(record => {
        const venueName = record.groundName || record.classRoomName;
        if (!venueMap.has(venueName)) {
          venueMap.set(venueName, {
            name: venueName,
            classRoomId: record.classRoomId,
            sportGroundId: record.sportGroundId,
            timeSlots: []
          });
        }
      });
    }
    
    return venueMap;
  }

  /**
   * 处理时间槽
   * @param {Map} venueMap - 场地Map
   * @param {Object} data - 原始场地数据
   */
  processTimeSlots(venueMap, data) {
    let groundData, useData;
    
    // 处理 { groundData: [...], useData: [...] } 结构
    if (data.groundData && data.useData) {
      groundData = data.groundData;
      useData = data.useData;
    } else {
      // 处理 { data: { records: [...] } } 结构
      const actualData = data.data || data;
      groundData = actualData.records;
      useData = []; // 在单数据结构中，没有单独的useData，设为空数组
    }
    
    venueMap.forEach((venue, venueName) => {
      // 解析价格JSON
      let priceMap = {};
      try {
        const record = groundData.find(r => (r.groundName || r.classRoomName) === venueName);
        if (record && record.priceJson) {
          const priceData = JSON.parse(record.priceJson);
          // 提取价格映射
          priceData.forEach(priceItem => {
            if (priceItem.timeList && priceItem.timeList.length > 0) {
              priceItem.timeList.forEach(timeItem => {
                if (timeItem.priceMap) {
                  Object.assign(priceMap, timeItem.priceMap);
                }
              });
            }
          });
        }
      } catch (e) {
        console.error('解析价格JSON失败:', e);
      }
      
      // 生成时间槽
      for (let hour = 6; hour <= 22; hour++) {
        for (let minute = 0; minute < 60; minute += 30) {
          const timeKey = minute === 0 ? hour.toString() : `${hour}.${minute === 30 ? '5' : '0'}`;
          const timeSlot = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}-${(hour + (minute + 30 >= 60 ? 1 : 0)).toString().padStart(2, '0')}:${((minute + 30) % 60).toString().padStart(2, '0')}`;
          
          const beginDatetime = `${this.selectedDate} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}:00`;
          const endDatetime = `${this.selectedDate} ${(hour + (minute + 30 >= 60 ? 1 : 0)).toString().padStart(2, '0')}:${((minute + 30) % 60).toString().padStart(2, '0')}:00`;
          
          // 获取价格
          const price = parseFloat(priceMap[timeKey]) || 30;
          
          // 检查时间槽是否已被预约
          let isFree = true;
          if (useData && useData.length > 0) {
            const venueRecord = groundData.find(r => (r.groundName || r.classRoomName) === venueName);
            if (venueRecord) {
              // 查找该场地在该时间段的使用记录
              const useRecords = useData.filter(u => 
                u.sportGroundId === venueRecord.sportGroundId && 
                u.classRoomId === venueRecord.classRoomId
              );
              
              if (useRecords.length > 0) {
                // 检查时间段是否冲突
                const slotStart = new Date(beginDatetime).getTime();
                const slotEnd = new Date(endDatetime).getTime();
                
                // 假设useRecords中有startDate和endDate字段表示预约时间
                const hasConflict = useRecords.some(useRecord => {
                  if (!useRecord.startDate || !useRecord.endDate) return false;
                  
                  const useStart = new Date(useRecord.startDate).getTime();
                  const useEnd = new Date(useRecord.endDate).getTime();
                  
                  // 检查时间是否有重叠
                  return slotStart < useEnd && slotEnd > useStart;
                });
                
                if (hasConflict) {
                  isFree = false;
                }
              }
            }
          }
          
          // 添加时间槽信息
          venue.timeSlots.push({
            time: timeSlot,
            isFree: isFree,
            price: price,
            beginDatetime: beginDatetime,
            endDatetime: endDatetime
          });
        }
      }
    });
  }

  /**
   * 转换为场地列表
   * @param {Map} venueMap - 场地Map
   * @returns {Array} 场地列表
   */
  convertToVenueList(venueMap) {
    return Array.from(venueMap.values()).map((venue, index) => {
      // 根据场地名称设置价格
      let price = 30; // 默认价格
      
      return {
        id: 20000 + index, // 给3.5+网球（新基）场地分配ID
        name: venue.name,
        address: "深圳市南山区西丽街道新基路",
        latitude: 22.6123,
        longitude: 113.9724,
        description: '3.5+网球（新基）',
        rating: 4.5,
        price: price,
        facilities: ['室内场地', '专业教练'],
        image: '',
        distance: 4.5,
        timeSlots: venue.timeSlots,
        dataSource: '3.5+网球（新基）'
      };
    });
  }

/**
 * 处理场地数据
 * @param {Object} data - 原始场地数据
 * @param {string} selectedDate - 选择的日期
 * @returns {Array} 处理后的场地列表
 */
process(data, selectedDate) {
  this.selectedDate = selectedDate;
  
  // 验证数据
  if (!this.validateData(data)) {
    console.error('3.5+网球（新基）数据验证失败');
    return [];
  }
  
  // 按场地名称分组
  const venueMap = this.groupVenues(data);
  
  // 处理时间槽
  this.processTimeSlots(venueMap, data);
  
  // 转换为场地列表
  return this.convertToVenueList(venueMap);
}
}

export default ThreePointFiveNewJiProcessor;